#!/usr/bin/ruby

# Processes meshes and prepares to upload them to the internets.
#
# Steps:
#   * Check size of the mesh is reasonable
#   * Check naming conventions
#   * Makes names unique in the mesh
#   * Creates a zip

#url = $*[0] or raise "Usage: rootify "

require 'ftools'

guid = "12345"
resource_prefix = "/id/" + guid + "/"
image_prefix = "resource_" + guid + "_"
url = "http://s3/wonderland/#{guid}"
tmpdir = "tmp/"

ogre_tools_location = "/wonderland/OgreSDK/Tools/"
ogre_xml_converter = ogre_tools_location + "OgreXMLConverter"

image_magick = "convert"
zipper = "zip"

`mkdir tmp; rm tmp/*`

Dir["*.material"].each do |material|
  
  File.open(tmpdir + material, "w") do |f|
    IO.readlines(material).each do |st|
      f.puts st.gsub(/^material /, "material " + resource_prefix).
        gsub(/^\s+texture\s"/, "texture " + image_prefix).
        gsub(/.png"/, ".jpg\"")
    end
  end

end

Dir["*.mesh"].each do |mesh|
  `#{ogre_xml_converter} #{mesh} -q`
end

Dir["*.mesh.xml"].each do |mesh|
  
  File.open(tmpdir + mesh, "w") do |f|
    IO.readlines(mesh).each do |st|
      f.puts st.
        gsub(/material="/, "material=\"" + resource_prefix)
    end
  end

  `cd #{tmpdir};#{ogre_xml_converter} -q #{mesh}; rm #{mesh}; cd -`
end

Dir["*.png"].each do |fn|
  `#{image_magick} -quality 80 #{fn} #{tmpdir}/#{fn.sub(/png^/i, 'jpg')}`
end

Dir["*.jpg"].each do |fn|
  File.copy(fn, tmpdir + "/" + fn)
end

Dir["*.skeleton"].each do |fn|
  File.copy(fn, tmpdir + "/" + fn)
end

`cd #{tmpdir};rm OgreXMLConverter.log; zip ../packaged.zip *; cd -`
